﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FriGHelper
{
    //调用其他非本端口接口使用方法
    public class PostHelper
    {
        public static string DoPost(string url, Dictionary<object, object> param)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (object key in param.Keys)
                {
                    object value = param[key];
                    sb.Append($"{key}={value}&");
                }

                string postData = sb.ToString();
                postData = postData.Substring(0, postData.Length - 1);

                byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;

                //打开request字符流
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                //定义response为前面的request响应
                WebResponse response = request.GetResponse();

                //获取相应的状态代码
                //Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                //定义response字符流
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();//读取所有

                //关闭资源
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
                return "12";
            }

        }
    }
}
